package com.chdwmp.product.pay.ali;

import com.alipay.api.internal.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public class AlipayUtil {

    public static String getSignContent(Map<String, String> sortedParams,Boolean isEncoder) throws Exception{
        StringBuffer content = new StringBuffer();
        ArrayList keys = new ArrayList(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;

        for (Object key1 : keys) {
            String key = (String) key1;
            String value = sortedParams.get(key);
            if (StringUtils.areNotEmpty(new String[]{key, value})) {
                if (isEncoder) {
                    content.append(index == 0 ? "" : "&").append(key).append("=").append(URLEncoder.encode(value,"utf-8"));
                }else {
                    content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                }
                ++index;
            }
        }

        return content.toString();
    }

    public static  Map<String, String> getRequestParams(HttpServletRequest request) throws Exception{
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        return params;
    }
}
